//index.js
//获取应用实例
const app = getApp()
// var template = require('../../template/template.js')
var ea = require('../../utils/each.js');
const socketOpen = false
const socketMsgQueue = []
Page({
  data: {
    pid:0,
    getindex:app.data.url+'/mapi/index/getindex',
    loginurl: app.data.url +'/mapi/index/login',
    addpidurl: app.data.url +'/mapi/index/addpid',
    binduidurl: app.data.url + '/mapi/index/binduid',
    motto: 'Hello World',
    souquan:true,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  imgUrls: [
      // '../../assets/d5.png',
      // 'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      // 'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    indicator: 'white',
    stas:false,
    vertical: true,
    circular: true,
    mesgs: [
    ],
  fangjian:[],
  coujiang:false,
    getfenxiangurl: app.data.url + '/mapi/newfenxiao/getfenxiang'
  },


  // 截获竖向滑动
  catchTouchMove: function (res) {
    return false
  },

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (option) {
    wx.showLoading({
      title: '加载中',
    })
    var pid ='';
    if (option&&option.scene){
      pid = option.scene;
    }
    var user = wx.getStorageSync('user');
    if (!user) {
      this.setData({ souquan: false });
    }
      if (pid) {
        this.getData(pid);
      } else {
        this.getData();
      }
  },
  getUserInfo: function(e) {
    var that = this;
    var user = e.detail.userInfo;
    that.setData({ souquan:true});
    if(that.data.pid>0){
      user.pid = that.data.pid;
    }
    console.log(user);
    wx.login({
      success:function(res){
        user.code = res.code;
        console.log(user);
        wx.request({
          url: that.data.loginurl,
          method:'post',
          data:user,
          success:function(res){
            var data = res.data;
            // console.log(data.data);
            if(data.code==200){
              wx.setStorageSync('user', data.data);
            }else{
              wx.showToast({
                title: data.msg,
                icon:'none'
              })
            }
          }
        }) 
      }
    })
  },
  getData:function(pid){
    if (pid) {
      this.setData({ pid: pid });
    }
    var that = this;
    var user = wx.getStorageSync('user');
    if(!user){
      that.setData({ souquan: false })
    }
    pid = this.data.pid;
    var tiaojian = { token: user.token };
    if (pid) {
      tiaojian.pid = pid;
    }
    if (pid) {
      // this.setData({ pid: pid});
      if (user) {
        wx.request({
          url: this.data.addpidurl,
          data: tiaojian,
          method: 'post',
          success: function (res) {
            var data = res.data;
            if (data.code == 200) {
              wx.setStorageSync('user', data.data);
            } else {
              wx.showToast({
                title: data.msg,
                icon: 'none'
              })
            }
          }
        })
      }
    }

    //检测是否有更新
    wx.getUpdateManager().onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log("是否有新版本：" + res.hasUpdate);
      if (res.hasUpdate) {//如果有新版本
        wx.showToast({
          title: '版本有更新',
          icon: 'none'
        })
        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateReady(function () {//当新版本下载完成，会进行回调
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，单击确定重启应用',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.getUpdateManager().applyUpdate();
              }
            }
          })

        })

        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateFailed(function () {//当新版本下载失败，会进行回调
          wx.showModal({
            title: '提示',
            content: '检查到有新版本，但下载失败，请检查网络设置',
            showCancel: false,
          })
        })
      }
    });
    wx.request({
      url: that.data.getindex,
      data: {},
      method: 'post',
      success: function (res) {
        var data = res.data;
        console.log(data);
        if (data.code == 200) {
          var imgUrls = [];
          var lunbo = data.data.lunbo;
          var coujiang = data.data.coujiang.dir;
          if (coujiang=='0'){
            that.setData({ coujiang: false });
          }else{
            that.setData({ coujiang: true });
          }
          that.setData({ imgUrls: lunbo });
          var messge = data.data.messge.data;
          // console.log(messge);
          messge = ea.jiequ(messge, 3);
          that.setData({ mesgs: messge });
          var fangjian = data.data.fangjian;
          that.setData({ fangjian: fangjian });
          console.log(fangjian);
          wx.hideLoading();
          var user = wx.getStorageSync('user');
          if(user){
            that.setData({ souquan: true });
          }

          // console.log(messge);
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      }
    })

    wx.getSetting({
      success: function (res) {
        console.log(res);
        if (!res.authSetting['scope.userInfo']) {
          that.setData({ souquan: false });
        }
      }
    })
  },

 tiaozhuan:function(e){
   console.log(e);
   var id = e.target.dataset.id;
   var coujiang = this.data.coujiang;
   if(!coujiang){
     wx.navigateTo({
       url: '/pages/huxin/huxin?id='+id,
     })
     return;
   }
   wx.navigateTo({
     url: '/pages/zhuanpan/zhuanpan?id='+id
   })
 },
  onShareAppMessage:function(){
    var user = wx.getStorageSync('user');
    var titles = wx.getStorageSync('titles');
    return {
      title:titles,
      path:'/pages/index/index?scene'+user.id,
    };
  }
  , onPullDownRefresh:function(){
    var pid = this.data.pid;
    this.onLoad({pid:pid});
    // console.log(wx.pageScrollTo);
    wx.stopPullDownRefresh({
      success:function(){
        console.log('返回了')
      }
    });
  },
  onShow:function(option){
    var pid = '';
    if(option&&option.scene){
      pid = option.scene;
    }
    var user = wx.getStorageSync('user');
    var that = this;
    if(!user){
      this.setData({ souquan:false});
    }else{
      if(pid){
        this.getData(pid);
      }else{
        this.getData();
      }
      wx.request({
        url: that.data.getfenxiangurl,
        data: { token: user.token },
        method: 'post',
        success: function (res) {
          var data = res.data;
          console.log(data);
          if(data.code==200){
            wx.setStorageSync('titles', data.data.dir)
          }
        }
      })
    }
  }
})
